package com.lzm.service.impl;

import com.lzm.domain.Seckill;
import com.lzm.domain.SuccessKilled;
import com.lzm.dto.Exposer;
import com.lzm.dto.SeckillExecution;
import com.lzm.enums.EncryptionEnum;
import com.lzm.enums.SeckillStatEnum;
import com.lzm.exception.SeckillException;
import com.lzm.repository.SeckillRepository;
import com.lzm.repository.SuccessKilledRepository;
import com.lzm.service.RedisService;
import com.lzm.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by codingBoy on 16/11/28.
 */
@Service
public class SeckillServiceImpl implements SeckillService {

    //日志对象
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //注入Service依赖
    @Resource
    private SeckillRepository seckillRepository;

    @Resource
    private SuccessKilledRepository successKilledRepository;

    @Resource
    private RedisService redisService;

    @Override
    public List<Seckill> findAll() {
        return seckillRepository.findAll();
    }

    @Override
    public Seckill findById(Long seckillId) {
        return seckillRepository.findOne(seckillId);
    }

    @Override
    public Exposer exportSeckillUrl(Long seckillId) {
        //优化点:缓存优化:超时的基础上维护一致性
        //1.访问redis
        Seckill seckill = redisService.getSeckill(seckillId);
        if (seckill == null) {
            //2.访问数据库
            seckill = seckillRepository.findOne(seckillId);
            if (seckill == null) {//说明查不到这个秒杀产品的记录
                return new Exposer(false, seckillId);
            }else {
                //3,放入redis
                redisService.putSeckill(seckill);
            }
        }

        //若是秒杀未开启
        Date startTime=seckill.getStartTime();
        Date endTime=seckill.getEndTime();
        //系统当前时间
        Date nowTime=new Date();
        if (startTime.getTime()>nowTime.getTime() || endTime.getTime()<nowTime.getTime()) {
            return new Exposer(false,seckillId,nowTime.getTime(),startTime.getTime(),endTime.getTime());
        }

        //秒杀开启，返回秒杀商品的id、用给接口加密的md5
        String md5=getMD5(seckillId);
        return new Exposer(true,md5,seckillId);
    }

    private String getMD5(Long seckillId) {
        //信息+盐值，加入一个混淆字符串(秒杀接口)的salt，为了我避免用户猜出我们的md5值，值任意给，越复杂越好
        String base = seckillId + "/" + EncryptionEnum.MD5_1.getKey();
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    /**
     * 使用注解控制事务方法的优点:
     * 1.开发团队达成一致约定，明确标注事务方法的编程风格
     * 2.保证事务方法的执行时间尽可能短，不要穿插其他网络操作RPC/HTTP请求或者剥离到事务方法外部
     * 3.不是所有的方法都需要事务，如只有一条修改操作、只读操作不要事务控制
     */
    //秒杀是否成功，成功:减库存，增加明细；失败:抛出异常，事务回滚
    @Override
    @Transactional
    public SeckillExecution executeSeckill(Long seckillId, Long userPhone, String md5) throws SeckillException {

        if (md5 == null|| !md5.equals(getMD5(seckillId))) {
            throw new SeckillException(SeckillStatEnum.DATE_REWRITE.getDescribe());//秒杀数据被重写了
        }
        //执行秒杀逻辑:减库存+增加购买明细
        Date nowTime = new Date();

        try{
            //否则更新了库存，秒杀成功,增加明细
            SuccessKilled successKilled = new SuccessKilled();
            successKilled.setSeckillId(seckillId);
            successKilled.setUserPhone(userPhone);
            SuccessKilled insertResult = successKilledRepository.save(successKilled);
            //看是否该明细被重复插入，即用户是否重复秒杀
            if (insertResult != null) {
                throw new SeckillException(SeckillStatEnum.REPEAT_KILL.getDescribe());
            }else {
                //减库存,热点商品竞争
                int updateCount = seckillRepository.reduceNumber(seckillId, nowTime);
                if (updateCount <= 0) {
                    //没有更新库存记录，说明秒杀结束 rollback
                    throw new SeckillException(SeckillStatEnum.END.getDescribe());
                }else {
                    //秒杀成功,得到成功插入的明细记录,并返回成功秒杀的信息 commit
                    SuccessKilled result = successKilledRepository.findOne((root, query, cb) -> {
                            List<Predicate> list = new ArrayList<>();
                            if (seckillId != null && userPhone != null) {
                                list.add(cb.equal(root.get("seckill_id").as(Long.class), seckillId));
                                list.add(cb.equal(root.get("user_phone").as(Long.class), userPhone));
                            }else {
                                throw new SeckillException(SeckillStatEnum.DATA_ILLEGAL.getDescribe());
                            }
                            Predicate[] p = new Predicate[list.size()];
                            return cb.and(list.toArray(p));

                    });
                    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, result);
                }
            }
        }catch (SeckillException e3){
            throw e3;
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            //所以编译期异常转化为运行期异常
            throw new SeckillException(SeckillStatEnum.INNER_ERROR.getDescribe());
        }
    }
}







